package cn.itsource.basic.service.impl;

import cn.itsource.basic.constant.VerificationConstant;
import cn.itsource.basic.exception.CustomException;
import cn.itsource.basic.util.SendMsgUtils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.basic.service.IVerificationService;
import com.sun.org.apache.xpath.internal.SourceTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class VerificationServiceImpl implements IVerificationService {
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送注册验证码
     * 验证码需求：
     *      1.后台随机产生4个字符
     *      2.1分钟以内只能发送1次验证码
     *      3.超过1分钟，但在5分钟以内，发送的验证码依然是第一次产生的验证码字符
     *      4.超过了5分钟以后，产生全新的验证码
     * @return
     */
    @Override
    public void sendVerificationCodeReg(String phone) throws CustomException {
        sendVerificationCode(phone,phone+":"+VerificationConstant.USER_REG);

    }

    @Override
    public void sendVerificationCodeBinder(String phone) throws CustomException {
        sendVerificationCode(phone,phone+":"+VerificationConstant.USER_Binder);
    }

    public void sendVerificationCode(String phone,String key) throws CustomException {
        //获取六位数的验证码
        String valueCode = StrUtils.getRandomString(6);
        //获取redis key
        String  value = (String) redisTemplate.opsForValue().get(key);
        //判断value是否为空 为空就不进去循环
        if (!StringUtils.isEmpty(value)){
            // 截取时间戳  判断是否在一分钟之内1分钟以内只能发送1次验证码
            String time = value.split(":")[1];
            if (System.currentTimeMillis()-Long.valueOf(time)>=60*1000){
                throw new CustomException("请不要一分钟之内重复发送验证码");
            }
            //超过1分钟，但在5分钟以内，发送的验证码依然是第一次产生的验证码字符
            valueCode = value.split(":")[0];
        }
        //设置key  k = phone:USER_REG   v = value ：时间戳
        redisTemplate.opsForValue().set(key , valueCode+":"+System.currentTimeMillis(),2, TimeUnit.MINUTES);
        System.out.println(valueCode);
        //发送短信
        //SendMsgUtils.send(phone, "尊敬的用户，您的心动码为"+valueCode+"请在两分钟之内发送给您的宝贝，领取奖励。");
    }

}
